<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\CategorySaveRequest;
use App\Http\Requests\CategoryUpdateRequest;
use App\Http\Responses\Response;
use App\Models\Category;
use Exception;
use Illuminate\Http\JsonResponse;

class CategoryController extends Controller
{
    public function list(): JsonResponse
    {
        // 查询所有的父分类
        $categories = Category::with("children")->withCount('posts')
            ->orderBy("cate_weight", "desc")
            ->get();

        return Response::resource_success($categories);
    }

    public function save(CategorySaveRequest $request): JsonResponse
    {

        $clean_data = $request->validated();

        if (!isset($clean_data["parent"])) {
            $clean_data["parent"] = null;
        }

        $category = Category::create([
            "cate_name" => $clean_data["name"],
            "cate_parent" => $clean_data["parent"],
            "cate_create_time" => date('Y-m-d H:i:s')
        ]);
        try {
            $category->save();
        } catch (Exception $exception) {
            return Response::insert_error();
        }

        return Response::insert_success($category);
    }

    public function update(CategoryUpdateRequest $request, $id): JsonResponse
    {

        $clean_data = $request->validated();

        $category = Category::find($id);

        if (is_null($category)) {
            return Response::update_error();
        }
        // insert into database
        if (isset($clean_data["name"])) {
            $category->cate_name = $clean_data["name"];
        }
        if (isset($clean_data["weight"])) {
            $category->cate_weight = $clean_data["weight"];
        }
        if (isset($clean_data["parent"])) {
            $category->cate_parent = $clean_data["parent"];
        }
        if (isset($clean_data["status"])) {
            $category->cate_status = $clean_data["status"];
        }
        try {
            $category->save();
        } catch (Exception $exception) {
            return Response::update_error();
        }

        return Response::update_success($category);
    }

    public function delete($id): JsonResponse
    {
        $category = Category::find($id);
        Category::destroy($id);
        if (Category::find($id)) {
            return Response::delete_error();
        }
        return Response::delete_success($category);
    }
}
